<script setup lang="ts">
import { ref, reactive, onMounted, computed, toRefs, nextTick } from 'vue'
import { ElTable, ElTableColumn, ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElDatePicker, ElMessageBox, ElMessage, ElTabPane, ElTabs, ElUpload, ElCheckbox } from 'element-plus'
import CommonLayout from '../components/CommonLayout.vue'
import SupplierSelect from '../components/SupplierSelect.vue'
import MaterialSelect from '../components/MaterialSelect.vue'
import { Search, Plus, Edit, Delete, Check, Close as X, Filter, Refresh, Download, ArrowRight, InfoFilled as Info, DollarSign, Calendar, Clock, User, Phone, Building, Tag, BarChart3 } from '@element-plus/icons-vue'
import * as purchaseOrderApi from '../api/purchaseOrder'
import { apiRequest } from '../utils/apiRequest'

// 优化：使用toRefs提升响应式体验
const { getPurchaseOrders, getPurchaseOrderById, createPurchaseOrder, updatePurchaseOrder, deletePurchaseOrder } = purchaseOrderApi

// 采购订单数据
const purchaseOrders = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索条件
const searchForm = reactive({
  orderNo: '',
  supplierId: '',
  supplierName: '',
  status: '',
  startDate: '',
  endDate: ''
})

// 供应商列表
const suppliers = ref([])
const materials = ref([])

// 对话框状态
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogType = ref('create') // 'create' 或 'update'
const currentOrder = ref({
  id: '',
  orderNo: '',
  supplierId: '',
  orderDate: '',
  expectedDeliveryDate: '',
  paymentTerms: '',
  deliveryMethod: '',
  freightBearer: '',
  remark: '',
  items: [] as any[]
})

// 订单状态映射
const statusMap = {
  0: '待审核',
  1: '已审核',
  2: '已关闭',
  3: '已取消'
}

// 格式化金额
const formatCurrency = (row, column, cellValue) => {
  return `¥${Number(cellValue).toFixed(2)}`
}

// 格式化状态
const formatStatus = (row, column, cellValue) => {
  return statusMap[cellValue]
}

// 格式化税率
const formatTaxRate = (row, column, cellValue) => {
  return `${Number(cellValue)}%`
}

// 获取采购订单列表 - 优化：增加错误详情反馈和多种响应格式支持
const fetchPurchaseOrders = async () => {
  loading.value = true
  try {
    const response = await getPurchaseOrders({
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    })
    console.log('Purchase orders API response:', response)
    
    // 处理不同格式的响应
    let ordersData = []
    let ordersTotal = 0
    
    if (response?.data?.items && response?.data?.total) {
      // 标准分页格式响应
      ordersData = response.data.items?.$values || response.data.items || []
      ordersTotal = response.data.total || 0
    } else if (response?.data?.$values) {
      // 带有$values属性的响应
      ordersData = response.data.$values || []
      ordersTotal = ordersData.length
    } else if (response?.$values) {
      // 根级别带有$values属性的响应
      ordersData = response.$values || []
      ordersTotal = ordersData.length
    } else if (Array.isArray(response?.data)) {
      // 数据直接在data中的数组
      ordersData = response.data || []
      ordersTotal = ordersData.length
    } else if (Array.isArray(response)) {
      // 直接返回数组
      ordersData = response || []
      ordersTotal = ordersData.length
    } else {
      // 默认处理
      ordersData = []
      ordersTotal = 0
    }
    
    console.log('Processed purchase orders data:', ordersData)
    purchaseOrders.value = ordersData
    total.value = ordersTotal
  } catch (error) {
    const errorMsg = error.response?.data?.message || '获取采购订单列表失败'
    ElMessage.error(errorMsg)
    console.error('Failed to get purchase orders:', error)
  } finally {
    loading.value = false
  }
}

// 获取供应商列表 - 优化：增加错误详情反馈和多种响应格式支持
const fetchSuppliers = async () => {
  try {
    console.log('Starting to fetch suppliers...')
    // 添加分页参数
    const response = await apiRequest.get('/api/suppliers', {
      params: {
        page: 1,
        pageSize: 100
      }
    })
    console.log('Suppliers API response:', response)
    
    // 处理不同格式的响应
    let suppliersData = []
    if (response?.items && response?.total) {
      // 分页格式响应
      // 检查items是否有$values属性
      suppliersData = response.items?.$values || response.items || []
    } else if (response?.$values) {
      // 带有$values属性的响应
      suppliersData = response.$values || []
    } else if (Array.isArray(response)) {
      // 直接返回数组
      suppliersData = response
    } else {
      // 默认处理
      suppliersData = []
    }
    
    console.log('Processed suppliers data:', suppliersData)
    suppliers.value = suppliersData
    
    // 检查是否有数据
    if (suppliers.value.length === 0) {
      console.log('No suppliers data available')
      ElMessage.info('没有找到供应商数据，请先创建供应商')
    } else {
      console.log('Suppliers count:', suppliers.value.length)
    }
  } catch (error) {
    const errorMsg = error.response?.data?.message || '获取供应商列表失败'
    ElMessage.error(errorMsg)
    console.error('Failed to get suppliers:', error)
    // 显示错误详情
    console.error('Error details:', error.response)
  }
}





// 处理供应商选择变化
const handleSupplierChange = (id) => {
  const selectedSupplier = suppliers.value.find(s => s.id === id)
  if (selectedSupplier) {
    // 直接更新响应式对象的属性
    searchForm.supplierId = id
    searchForm.supplierName = selectedSupplier.supplierName
  } else {
    searchForm.supplierId = ''
    searchForm.supplierName = ''
  }
  // 强制刷新搜索参数
  handleSearch()
}

// 处理状态选择变化
const handleStatusChange = (status) => {
  // 强制UI更新
  searchForm.status = status
}

// 搜索采购订单
const handleSearch = () => {
  currentPage.value = 1
  fetchPurchaseOrders()
}

// 重置搜索条件
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key as keyof typeof searchForm] = ''
  })
  currentPage.value = 1
  fetchPurchaseOrders()
}

// 打开对话框 - 优化：使用函数式重置表单
const openDialog = (type: 'create' | 'update', order: any = {}) => {
  dialogType.value = type
  if (type === 'create') {
    resetOrderForm()
  } else {
    // 深拷贝订单数据避免直接修改原数据
    currentOrder.value = JSON.parse(JSON.stringify(order))
    // 转换日期格式
    if (currentOrder.value.orderDate) {
      currentOrder.value.orderDate = new Date(currentOrder.value.orderDate)
    }
    if (currentOrder.value.expectedDeliveryDate) {
      currentOrder.value.expectedDeliveryDate = new Date(currentOrder.value.expectedDeliveryDate)
    }
  }
  dialogVisible.value = true
}

// 重置订单表单
const resetOrderForm = () => {
  currentOrder.value = {
    id: '',
    orderNo: '',
    supplierId: '',
    orderDate: new Date(),
    expectedDeliveryDate: '',
    paymentTerms: '',
    deliveryMethod: '',
    freightBearer: '',
    remark: '',
    items: [] as any[]
  }
}

// 查看订单详情
const viewOrderDetail = async (id: string) => {
  try {
    const response = await purchaseOrderApi.getPurchaseOrderById(id)
    currentOrder.value = response.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取订单详情失败')
    console.error('Failed to get order detail:', error)
  }
}

// 添加订单明细 - 优化：预设默认值和行号自增
const addOrderItem = () => {
  const newItem = {
    lineNo: currentOrder.value.items.length + 1,
    materialId: '',
    quantity: 1,
    unitPrice: 0,
    remark: '',
    amount: 0
  }
  
  currentOrder.value.items.push(newItem)
  // 自动聚焦到新添加的行
  nextTick(() => {
    const lastIndex = currentOrder.value.items.length - 1
    // 这里可以添加自动聚焦逻辑，如果有需要
  })
}

// 移除订单明细
const removeOrderItem = (index: number) => {
  currentOrder.value.items.splice(index, 1)
}

// 计算订单总金额
const totalAmount = computed(() => {
  return currentOrder.value.items.reduce((sum, item) => {
    return sum + (item.quantity || 0) * (item.unitPrice || 0)
  }, 0)
})

// 保存采购订单 - 优化：增强错误反馈和表单验证
const saveOrder = async () => {
  // 表单验证
  if (!currentOrder.value.supplierId) {
    ElMessage.warning('请选择供应商')
    return
  }
  if (!currentOrder.value.orderDate) {
    ElMessage.warning('请选择订单日期')
    return
  }
  if (currentOrder.value.items.length === 0) {
    ElMessage.warning('请添加订单明细')
    return
  }

  // 验证每个明细行
  for (const item of currentOrder.value.items) {
    if (!item.materialId) {
      ElMessage.warning('请选择物料')
      return
    }
    if (item.quantity <= 0) {
      ElMessage.warning('数量必须大于0')
      return
    }
    if (item.unitPrice < 0) {
      ElMessage.warning('单价不能小于0')
      return
    }
  }

  try {
    if (dialogType.value === 'create') {
      await createPurchaseOrder(currentOrder.value)
      ElMessage.success('创建采购订单成功')
    } else {
      await updatePurchaseOrder(currentOrder.value.id, currentOrder.value)
      ElMessage.success('更新采购订单成功')
    }
    dialogVisible.value = false
    fetchPurchaseOrders()
  } catch (error) {
    const errorMsg = error.response?.data?.message || (dialogType.value === 'create' ? '创建采购订单失败' : '更新采购订单失败')
    ElMessage.error(errorMsg)
    console.error(`${dialogType.value === 'create' ? 'Creating' : 'Updating'} purchase order failed:`, error)
  }
}

// 删除采购订单 - 优化：增加确认对话框和错误反馈
const handleDelete = async (id: string) => {
  try {
    const confirmResult = await ElMessageBox.confirm(
      '确定要删除此采购订单吗？此操作不可撤销！',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (confirmResult === 'confirm') {
      await deletePurchaseOrder(id)
      ElMessage.success('删除采购订单成功')
      fetchPurchaseOrders()
    }
  } catch (error) {
    if (error !== 'cancel') {
      const errorMsg = error.response?.data?.message || '删除采购订单失败'
      ElMessage.error(errorMsg)
      console.error('Failed to delete purchase order:', error)
    }
  }
}

// 审核采购订单 - 优化：增加审核人信息和错误反馈
const handleReview = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定要审核此采购订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    // 实际应用中，审核人应该从当前登录用户获取
    const reviewedBy = '1' // 临时使用1作为用户ID
    const isApproved = true
    const comments = '审核通过'
    
    await apiRequest.put(`/api/PurchaseOrders/${id}/review`, {
      ReviewedBy: reviewedBy,
      IsApproved: isApproved,
      Comments: comments
    })
    
    ElMessage.success('审核采购订单成功')
    fetchPurchaseOrders()
  } catch (error) {
    if (error === 'cancel') return
    const errorMsg = error.response?.data?.message || '审核采购订单失败'
    ElMessage.error(errorMsg)
    console.error('Failed to review purchase order:', error)
  }
}

// 关闭采购订单 - 优化：增加关闭人信息和错误反馈
const handleClose = async (id: string) => {
  try {
    await ElMessageBox.confirm('确定要关闭此采购订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    // 实际应用中，关闭人应该从当前登录用户获取
    const closedBy = '1' // 临时使用1作为用户ID
    const reason = '订单已完成'
    
    await apiRequest.put(`/api/PurchaseOrders/${id}/close`, {
      ClosedBy: closedBy,
      Reason: reason
    })
    
    ElMessage.success('关闭采购订单成功')
    fetchPurchaseOrders()
  } catch (error) {
    if (error === 'cancel') return
    const errorMsg = error.response?.data?.message || '关闭采购订单失败'
    ElMessage.error(errorMsg)
    console.error('Failed to close purchase order:', error)
  }
}

// 导出采购订单
const exportOrders = () => {
  // 实现导出功能
  ElMessage.info('导出功能待实现')
}

// 页面加载时执行
// 获取物料列表 - 优化：增加错误详情反馈和多种响应格式支持
const fetchMaterials = async () => {
  try {
    console.log('Starting to fetch materials...')
    const response = await apiRequest.get('/api/materials')
    console.log('Materials API response:', response)
    
    // 处理不同格式的响应
    let materialsData = []
    
    if (response?.data?.items && response?.data?.total) {
      // 分页格式响应
      materialsData = response.data.items?.$values || response.data.items || []
    } else if (response?.data?.$values) {
      // 带有$values属性的响应
      materialsData = response.data.$values || []
    } else if (response?.$values) {
      // 根级别带有$values属性的响应
      materialsData = response.$values || []
    } else if (Array.isArray(response?.data)) {
      // 数据直接在data中的数组
      materialsData = response.data || []
    } else if (Array.isArray(response)) {
      // 直接返回数组
      materialsData = response || []
    } else {
      // 默认处理
      materialsData = []
    }
    
    console.log('Processed materials data:', materialsData)
    materials.value = materialsData
    
    // 检查是否有数据
    if (materials.value.length === 0) {
      console.log('No materials data available')
      ElMessage.info('没有找到物料数据，请先创建物料')
    } else {
      console.log('Materials count:', materials.value.length)
    }
  } catch (error) {
    const errorMsg = error.response?.data?.message || '获取物料列表失败'
    ElMessage.error(errorMsg)
    console.error('Failed to get materials:', error)
  }
}

// 优化：合并初始化函数，使用Promise.all并行请求
const initData = async () => {
  try {
    await Promise.all([
      fetchPurchaseOrders(),
      fetchSuppliers(),
      fetchMaterials()
    ])
  } catch (error) {
    console.error('Initialization failed:', error)
  }
}

// 页面加载时执行
onMounted(() => {
  initData()
})
</script>

<template>
  <common-layout title="采购订单">
    <template #header-buttons>
      <div class="buttons">
        <el-button type="primary" @click="openDialog('create')">
          <el-icon><Plus /></el-icon>
          新建订单
        </el-button>
        <el-button @click="exportOrders">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </template>

    <template #search-form>
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单编号" style="width: 260px;">
          <ElInput v-model="searchForm.orderNo" placeholder="请输入订单编号" />
      </el-form-item>
      <el-form-item label="供应商" style="width: 260px;">
        <SupplierSelect v-model="searchForm.supplierId" placeholder="请选择供应商" @change="handleSupplierChange" />
      </el-form-item>
      <el-form-item label="状态" style="width: 260px;">
        <ElSelect v-model="searchForm.status" placeholder="请选择状态" @change="handleStatusChange">
          <ElOption v-for="(label, key) in statusMap" :key="key" :label="label" :value="key" />
        </ElSelect>
      </el-form-item>
      <el-form-item label="创建日期" style="width: 260px;">
        <ElDatePicker v-model="searchForm.startDate" type="date" placeholder="开始日期" />
        <span style="margin: 0 10px;">至</span>
        <ElDatePicker v-model="searchForm.endDate" type="date" placeholder="结束日期" />
      </el-form-item>
      <el-form-item>
        <ElButton type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </ElButton>
        <ElButton @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </ElButton>
      </el-form-item>
    </el-form>
    </template>

    <template #data-content>
    <!-- 采购订单列表 -->
    <el-table :data="purchaseOrders" v-loading="loading" border style="width: 100%">
        <ElTableColumn prop="orderNo" label="订单编号" width="180" />
        <ElTableColumn prop="supplierName" label="供应商" width="180" />
        <ElTableColumn prop="totalAmount" label="订单金额" width="120" :formatter="formatCurrency" />
        <ElTableColumn prop="status" label="状态" width="100" :formatter="formatStatus" />
        <ElTableColumn prop="orderDate" label="订单日期" width="180" />
        <ElTableColumn prop="expectedDeliveryDate" label="期望到货日期" width="180" />
        <ElTableColumn prop="creator" label="创建人" width="120" />
        <ElTableColumn label="操作" width="240" fixed="right">
          <template #default="scope">
            <ElButton size="small" @click="viewOrderDetail(scope.row.id)" :icon="Info">
              详情
            </ElButton>
            <ElButton size="small" @click="openDialog('update', scope.row)" :icon="Edit">
              编辑
            </ElButton>
            <ElButton size="small" type="danger" @click="handleDelete(scope.row.id)" :icon="Delete">
              删除
            </ElButton>
            <ElButton size="small" type="primary" v-if="scope.row.status === 0" @click="handleReview(scope.row.id)" :icon="Check">
              审核
            </ElButton>
            <ElButton size="small" v-if="scope.row.status === 1" @click="handleClose(scope.row.id)" :icon="X">
              关闭
            </ElButton>
          </template>
        </ElTableColumn>
    </el-table>
    </template>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="fetchPurchaseOrders"
        @current-change="fetchPurchaseOrders"
      />
    </div>
  </common-layout>

    <!-- 创建/编辑订单对话框 -->
    <ElDialog v-model="dialogVisible" :title="dialogType === 'create' ? '创建采购订单' : '编辑采购订单'" width="900px">
      <ElForm :model="currentOrder" label-width="120px">
        <ElTabs type="border-card">
          <ElTabPane label="基本信息">
            <ElFormItem label="订单编号" v-if="dialogType === 'update'">
              <ElInput v-model="currentOrder.orderNo" disabled />
            </ElFormItem>
            <ElFormItem label="供应商" prop="supplierId">
              <SupplierSelect v-model="currentOrder.supplierId" placeholder="请选择供应商" required />
            </ElFormItem>
            <ElFormItem label="订单日期" prop="orderDate">
              <ElDatePicker v-model="currentOrder.orderDate" type="date" placeholder="请选择订单日期" required />
            </ElFormItem>
            <ElFormItem label="期望到货日期" prop="expectedDeliveryDate">
              <ElDatePicker v-model="currentOrder.expectedDeliveryDate" type="date" placeholder="请选择期望到货日期" />
            </ElFormItem>
            <ElFormItem label="付款条件" prop="paymentTerms">
              <ElInput v-model="currentOrder.paymentTerms" placeholder="请输入付款条件" />
            </ElFormItem>
            <ElFormItem label="交货方式" prop="deliveryMethod">
              <ElInput v-model="currentOrder.deliveryMethod" placeholder="请输入交货方式" />
            </ElFormItem>
            <ElFormItem label="运费承担" prop="freightBearer">
              <ElInput v-model="currentOrder.freightBearer" placeholder="请输入运费承担方" />
            </ElFormItem>
            <ElFormItem label="备注" prop="remark">
              <ElInput v-model="currentOrder.remark" type="textarea" placeholder="请输入备注" />
            </ElFormItem>
          </ElTabPane>
          <ElTabPane label="订单明细">
            <ElTable :data="currentOrder.items" border style="width: 100%">
              <ElTableColumn label="物料名称" width="200">
                <template #default="scope">
                  <MaterialSelect v-model="scope.row.materialId" placeholder="请选择物料" />
                </template>
              </ElTableColumn>
              <ElTableColumn label="规格型号" width="180">
                <template #default="scope">
                  {{ materials.find(m => m.id === scope.row.materialId)?.specification || '-' }}
                </template>
              </ElTableColumn>
              <ElTableColumn label="单位" width="80">
                <template #default="scope">
                  {{ materials.find(m => m.id === scope.row.materialId)?.unit || '-' }}
                </template>
              </ElTableColumn>
              <ElTableColumn label="数量" width="80">
                <template #default="scope">
                  <ElInput v-model.number="scope.row.quantity" type="number" min="1" placeholder="输入数量" />
                </template>
              </ElTableColumn>
              <ElTableColumn label="单价" width="100">
                <template #default="scope">
                  <ElInput v-model.number="scope.row.unitPrice" type="number" min="0" placeholder="输入单价" />
                </template>
              </ElTableColumn>
              <ElTableColumn label="金额" width="100" :formatter="formatCurrency" />
              <ElTableColumn label="备注" width="150">
                <template #default="scope">
                  <ElInput v-model="scope.row.remark" placeholder="输入备注" />
                </template>
              </ElTableColumn>
              <ElTableColumn label="操作" width="80">
                <template #default="scope">
                  <ElButton size="small" type="danger" @click="removeOrderItem(scope.$index)">
                    删除
                  </ElButton>
                </template>
              </ElTableColumn>
            </ElTable>
            <div class="order-summary">
              <div class="total-amount">
                <span>订单总金额：</span>
                <span class="amount-value">{{ `¥${totalAmount.toFixed(2)}` }}</span>
              </div>
              <ElButton type="primary" size="small" @click="addOrderItem">
                添加明细
              </ElButton>
            </div>
          </ElTabPane>
        </ElTabs>
      </ElForm>
      <template #footer>
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="saveOrder">确定</ElButton>
      </template>
    </ElDialog>

    <!-- 订单详情对话框 -->
    <ElDialog v-model="detailDialogVisible" title="采购订单详情" width="900px">
      <ElTabs type="border-card">
        <ElTabPane label="基本信息">
          <div class="detail-info">
            <div class="info-row">
              <div class="info-label">订单编号：</div>
              <div class="info-value">{{ currentOrder.orderNo }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">供应商：</div>
              <div class="info-value">{{ currentOrder.supplierName }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">订单日期：</div>
              <div class="info-value">{{ currentOrder.orderDate }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">期望到货日期：</div>
              <div class="info-value">{{ currentOrder.expectedDeliveryDate }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">实际到货日期：</div>
              <div class="info-value">{{ currentOrder.actualDeliveryDate || '-' }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">订单状态：</div>
              <div class="info-value">{{ statusMap[currentOrder.status] }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">付款条件：</div>
              <div class="info-value">{{ currentOrder.paymentTerms || '-' }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">交货方式：</div>
              <div class="info-value">{{ currentOrder.deliveryMethod || '-' }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">运费承担：</div>
              <div class="info-value">{{ currentOrder.freightBearer || '-' }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">订单总金额：</div>
              <div class="info-value">{{ `¥${currentOrder.totalAmount?.toFixed(2) || '0.00'}` }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">已付金额：</div>
              <div class="info-value">{{ `¥${currentOrder.paidAmount?.toFixed(2) || '0.00'}` }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">未付金额：</div>
              <div class="info-value">{{ `¥${currentOrder.unpaidAmount?.toFixed(2) || '0.00'}` }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">创建人：</div>
              <div class="info-value">{{ currentOrder.creator || '-' }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">创建时间：</div>
              <div class="info-value">{{ currentOrder.createTime || '-' }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">审核人：</div>
              <div class="info-value">{{ currentOrder.reviewer || '-' }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">审核时间：</div>
              <div class="info-value">{{ currentOrder.reviewTime || '-' }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">关闭人：</div>
              <div class="info-value">{{ currentOrder.closer || '-' }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">关闭时间：</div>
              <div class="info-value">{{ currentOrder.closeTime || '-' }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">关闭原因：</div>
              <div class="info-value">{{ currentOrder.closeReason || '-' }}</div>
            </div>
            <div class="info-row">
              <div class="info-label">备注：</div>
              <div class="info-value">{{ currentOrder.remark || '-' }}</div>
            </div>
          </div>
        </ElTabPane>
        <ElTabPane label="订单明细">
          <ElTable :data="currentOrder.items" border style="width: 100%">
            <ElTableColumn prop="lineNo" label="行号" width="80" />
            <ElTableColumn prop="materialCode" label="物料编码" width="120" />
            <ElTableColumn prop="materialName" label="物料名称" width="180" />
            <ElTableColumn prop="specification" label="规格型号" width="180" />
            <ElTableColumn prop="unit" label="单位" width="80" />
            <ElTableColumn prop="quantity" label="数量" width="80" />
            <ElTableColumn prop="unitPrice" label="单价" width="100" :formatter="formatCurrency" />
            <ElTableColumn prop="amount" label="金额" width="100" :formatter="formatCurrency" />
            <ElTableColumn prop="taxRate" label="税率" width="80" :formatter="formatTaxRate" />
            <ElTableColumn prop="taxAmount" label="税额" width="100" :formatter="formatCurrency" />
            <ElTableColumn prop="totalAmount" label="价税合计" width="120" :formatter="formatCurrency" />
            <ElTableColumn prop="remark" label="备注" width="150" />
          </ElTable>
        </ElTabPane>
      </ElTabs>
      <template #footer>
        <ElButton @click="detailDialogVisible = false">关闭</ElButton>
      </template>
    </ElDialog>
</template>

<style scoped>
.app-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.buttons {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.order-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.total-amount {
  font-weight: bold;
}

.amount-value {
  color: #f56c6c;
  margin-left: 10px;
}

.detail-info {
  padding: 10px;
}

.info-row {
  display: flex;
  margin-bottom: 12px;
}

.info-label {
  width: 120px;
  text-align: right;
  font-weight: bold;
  margin-right: 10px;
}

.info-value {
  flex: 1;
}

.order-details {
  margin-top: 16px;
}

.order-item {
  margin-bottom: 8px;
}

.label {
  font-weight: bold;
  margin-right: 8px;
}
</style>